from django.shortcuts import render
from django.views import View
from alipay import AliPay
from django.conf import settings
from django import http
import os

from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJSONMixin,LoginRequiredMixin
from orders.models import OrderInfo
from .models import Payment
# Create your views here.


class PaymentStatusView(LoginRequiredJSONMixin, View):
    """保存支付的订单状态"""
    # def get(self,request):
    #     # 获取所有的查询字符串参数
    #     query_dict = request.GET
    #     # 将查询字符串参数的类型 转 标准的字典类型 (接口文档要求)
    #     data = query_dict.dict()
    #
    #     # 从查询字符串参数中 提取并移除 sign 不参与签名验证
    #     signature = data.pop('sign')
    #
    #     # 创建SDK对象
    #     alipay = AliPay(  # 传入公共参数(对接任何接口 都需要传递)
    #         appid=settings.ALIPAY_APPID,  # 应用ID
    #         app_notify_url=None,  # 默认回调url,如果采用同步通知就不许要传
    #         # 应用的私钥路径
    #         app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
    #         # 支付宝公钥路径
    #         alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
    #                                             "keys/alipay_public_key.pem"),
    #         sign_type="RSA2",  # 加密标准
    #         debug=settings.ALIPAY_DEBUG,  # 指定是否为开发环境
    #     )
    #
    #
    #     # 使用SDK对象,调用验证接口函数, 得到验证结果
    #     success = alipay.verify(data, signature)
    #
    #     # 如果验证通过, 需要将支付宝支付状态进行处理(将美多商城订单id和支付宝订单id绑定,修改订单状态)
    #     if success:
    #         # 美多商城的订单id
    #         order_id = data.get('out_trade_no'),
    #         # 支付宝的订单id
    #         trade_no = data.get('trade_no'),
    #         # Payment.objects.create(
    #         #     # order = order
    #         #     # order_id = order_id
    #         #     order_id = order_id,
    #         #     trade_id = trade_no,
    #         # )
    #         # # 修改订单的状态 由 ' 待支付 ' 修改 '待评价'
    #         # OrderInfo.filter(order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'].updata(status= OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']))
    #
    #         # 构造响应数据
    #         context = {
    #             'trade_no': trade_no,
    #         }
    #
    #         # 响应结果
    #         return render(request, 'pay_success.html', context)
    #
    #     else:
    #
    #         return http.HttpResponseForbidden('非法请求')

    def get(self, request):
        # 1.接收参数
        dict_data = request.GET
        data = dict_data.dict()

        # 删除这里的一个值(支付宝规定的)
        signature = data.pop("sign")
        from alipay import AliPay
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 对接支付宝,进行订单号的核验
        sucess = alipay.verify(data, signature)
        # 如果成功对接,
        if sucess:
            # 获取参数(订单单号id, 支付宝交易单号id)
            order_id = data.get("out_trade_no")
            trade_id = data.get("trade_no")

            # 修改数据库,创建表
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 并修改订单状态,从未支付改成未评价,因为已经购买过了,剩下的就是评价与未评价了
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            # 返回前段成功的回调页面
            context = {
                "trade_id": trade_id
            }
            return render(request, "pay_success.html", context)
        else:
            return http.HttpResponseForbidden("交易失败!")






class PaymentView(LoginRequiredJSONMixin,View):
    """对接支付宝的支付接口"""
    def get(self,request, order_id):
        """

        :param order_id: 当前要支付的订单ID
        :return: JSON
        """
        user = request.user
        # 校验order_id
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotEist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建对接支付宝接口的SDK对象
        alipay = AliPay(  # 传入公共参数(对接任何接口 都需要传递)
            appid=settings.ALIPAY_APPID,  # 应用ID
            app_notify_url=None,  # 默认回调url,如果采用同步通知就不许要传
            # 应用的私钥路径
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            # 支付宝公钥路径
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2", # 加密标准
            debug=settings.ALIPAY_DEBUG # 指定是否为开发环境
        )

        # SDK对象对接支付宝支付的接口.得到登陆页的地址
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单的编号
            total_amount=str(order.total_amount),  # 订单支付金额
            subject="美多商城%s" % order_id,  # 订单标题
            return_url=settings.ALIPAY_RETURN_URL, # 同步通知的回调地址,如果不是同步通知, 就不传
        )


        # 拼接完整的支付登陆页地址
        # 正式 : https://openapi.alipay.com/gateway.do? + order_string
        # 测试 : https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg':'ok', 'alipay_url': alipay_url})
